package com.zb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.constant.CodeConstant;
import com.zb.entity.*;
import com.zb.extend.CodeLogExtend;
import com.zb.mapper.ZjCodeUserRegisterMapper;
import com.zb.service.*;
import com.zb.vo.CodeRegisterAddressVo;
import com.zb.vo.CodeUserChangeLogVo;
import com.zb.vo.CodeUserRegisterVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 编码用户登记表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-09-04
 */
@Service
public class ZjCodeUserRegisterServiceImpl extends ServiceImpl<ZjCodeUserRegisterMapper, ZjCodeUserRegister> implements ZjCodeUserRegisterService {
    @Resource
    private ZjCodeUserRegisterMapper codeUserRegisterMapper;
    @Resource
    private ZjCodeService codeService;
    @Resource
    private ZjUserService userService;
    @Resource
    private ZjCodeUserChangeLogService codeUserChangeLogService;
    @Resource
    private ZjCodeLogService codeLogService;
    @Resource
    private ZjCodeUserAddressChangeLogService codeUserAddressChangeLogService;


    // 编码关联用户登记
    @Override
    @Transactional
    public void saveCodeRegister(AccounLoginInfo loginInfo, Long codeId, CodeUserRegisterVo userRegisterVo) {
        ZjCodeUserRegister register = new ZjCodeUserRegister();
        BeanUtils.copyProperties(userRegisterVo, register);

        String name = "";
        StringBuilder builder = new StringBuilder();
        if (null == register.getId() && null == codeUserRegisterMapper.isRegisterById(codeId)) {
            name = "新增用户登记且关联编码";
            builder.append("用户登记且关联编码，并激活编码与编码质保中");
            register.setId(codeId);
            register.setCustAccId(loginInfo.getCustAccId());
            this.save(register);
        } else {
            name = "修改用户登记";
            ZjCodeUserRegister userRegister = this.getById(register.getId());
            if (!Objects.equals(userRegister.getName(), register.getName())) {
                builder.append("登记用户姓名：").append(userRegister.getName()).append(" 更改为 ").append(register.getName()).append("；");
            }
            if (!Objects.equals(userRegister.getPhone(), register.getPhone())) {
                builder.append("登记用户手机号：").append(userRegister.getPhone()).append(" 更改为 ").append(register.getPhone()).append("；");
            }
            if (!Objects.equals(userRegister.getProvince(), register.getProvince()) || !Objects.equals(userRegister.getCity(), register.getCity())
                    || !Objects.equals(userRegister.getArea(), register.getArea()) || !Objects.equals(userRegister.getTown(), register.getTown())
                    || !Objects.equals(userRegister.getAddress(), register.getAddress())) {
                builder.append("登记地址：")
                        .append(userRegister.getProvince()).append("-")
                        .append(userRegister.getCity()).append("-")
                        .append(userRegister.getArea()).append("-");
                if (StringUtils.isNotBlank(userRegister.getTown())) builder.append(userRegister.getTown()).append("-");
                builder.append(userRegister.getAddress()).append(" 更改为 ")
                        .append(register.getProvince()).append("-")
                        .append(register.getCity()).append("-")
                        .append(register.getArea()).append("-");
                if (StringUtils.isNotBlank(register.getTown())) builder.append(register.getTown()).append("-");
                builder.append(register.getAddress()).append("；");
            }
            this.updateById(register);
        }
        codeService.updateCodeInfoByRegister(loginInfo, codeId, name, builder.toString());
    }

    // 保存变更用户
    @Override
    @Transactional
    public void saveChangeCodeUser(AccounLoginInfo loginInfo, CodeUserChangeLogVo userRegisterVo) {
         Assert.isTrue(null != userRegisterVo.getId(), "编码用户登记ID不能为空");
        ZjCodeUserRegister userRegister = this.getById(userRegisterVo.getId());
        Assert.notNull(userRegister, "编码变更用户登记参数[" + userRegisterVo.getId() + "]的数据不存在！");
        // 查询登记信息是否变动
        Assert.isTrue(!Objects.equals(userRegister.getUserId(), userRegisterVo.getUserId())
                || !Objects.equals(userRegister.getPhone(), userRegisterVo.getPhone()), "不可变更为同一个用户，如需变更请选择不同的用户！");

        if (null == userRegisterVo.getUserId() || 0 == userRegisterVo.getUserId()) {
            UserInfo user = new UserInfo();
            BeanUtils.copyProperties(userRegisterVo, user);
            Long userId = userService.save(loginInfo, user);
            userRegisterVo.setUserId(userId);
        }
        Integer tableType = codeService.getTableTypeById(userRegisterVo.getId());

        ZjCodeUserRegister register = new ZjCodeUserRegister();
        BeanUtils.copyProperties(userRegisterVo, register);
        this.updateById(register);

        ZjCodeUserChangeLog userChangeLog = new ZjCodeUserChangeLog();
        BeanUtils.copyProperties(userRegisterVo, userChangeLog);
        userChangeLog.setId(IdWorker.getId());
        userChangeLog.setCustAccId(loginInfo.getCustAccId());
        userChangeLog.setCodeId(register.getId());
        userChangeLog.setUsername(userRegisterVo.getName());
        userChangeLog.setCreateEmpId(loginInfo.getId());
        userChangeLog.setCreateEmp(loginInfo.getName());
        codeUserChangeLogService.save(userChangeLog);

        StringBuilder builder = new StringBuilder();
        builder.append("变更用户：")
                .append(userRegister.getName()).append(" ").append(userRegister.getPhone()).append(" 变更为 ")
                .append(register.getName()).append(" ").append(register.getPhone());
        ZjCodeLog codeLog = new CodeLogExtend(loginInfo, CodeConstant.CODE_LOG_TYPE_1, register.getId(), "变更用户", builder.toString());
        codeLogService.save(tableType -1, codeLog);
    }

    // 根据ID获取登记用户信息
    @Override
    public List<ZjCodeUserRegister> getByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjCodeUserRegister> wrapper = new QueryWrapper<>();
        wrapper.in("id", ids);
        return this.list(wrapper);
    }

    // 变更用户登记地址
    @Override
    @Transactional
    public void updateCodeRegisterAddress(AccounLoginInfo loginInfo, Long codeId, CodeRegisterAddressVo addressVo) {
        ZjCodeUserRegister register = this.getById(codeId);

        ZjCodeUserRegister newRegisterAddr = new ZjCodeUserRegister();
        BeanUtils.copyProperties(addressVo, newRegisterAddr);
        newRegisterAddr.setId(register.getId());
        this.updateById(newRegisterAddr);


        ZjCodeUserAddressChangeLog addressChangeLog = new ZjCodeUserAddressChangeLog();
        BeanUtils.copyProperties(register, addressChangeLog);
        addressChangeLog.setUsername(register.getName());
        addressChangeLog.setId(IdWorker.getId());
        addressChangeLog.setCodeId(codeId);
        addressChangeLog.setCreateEmpId(loginInfo.getId());
        addressChangeLog.setCreateEmp(loginInfo.getName());
        codeUserAddressChangeLogService.save(addressChangeLog);

        StringBuilder builder = new StringBuilder("变更登记地址：");
        builder.append(register.getProvince()).append("-")
                .append(register.getCity()).append("-")
                .append(register.getArea()).append("-");
        if (StringUtils.isNotBlank(register.getTown())) builder.append(register.getTown()).append("-");
        builder.append(register.getAddress())
                .append(" -> ")
                .append(addressVo.getProvince()).append("-")
                .append(addressVo.getCity()).append("-")
                .append(addressVo.getArea()).append("-");
        if (StringUtils.isNotBlank(addressVo.getTown())) builder.append(addressVo.getTown()).append("-");
        builder.append(addressVo.getAddress());

        ZjCodeLog log = new CodeLogExtend(loginInfo, CodeConstant.CODE_LOG_TYPE_1, codeId, "变更客户登记地址", builder.toString());
        codeLogService.save((int)(log.getCodeId() % 5), log);
    }

    // 根据客户ID获取编码登记信息
    @Override
    public List<ZjCodeUserRegister> getByUserIds(List<Long> userIds) {
        if (CollectionUtil.isEmpty(userIds)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjCodeUserRegister> wrapper = new QueryWrapper<>();
        wrapper.select("user_id");
        wrapper.in("user_id", userIds);
        return this.list(wrapper);
    }

}
